<template>
  <div>
    <el-divider content-position="left">轮播列表</el-divider>
    <el-button style="margin-right: 90%" type="text" @click="dialog = true"
      >添加</el-button
    >
    <div>
      <el-table :data="tableData" :key="Math.random()" style="width: 100%">
        <el-table-column prop="id" label="id" width="180"> </el-table-column>
        <el-table-column prop="src" label="图片" width="420">
          <template slot-scope="scope">
            <el-popover placement="bottom" title="" width="200" trigger="click">
              <!-- :src="require('@/assets/img/' + scope.row.src)" -->
              <el-image
                style="width: 960px; height: 320px"
                :src="scope.row.src"
              ></el-image>
              <el-button slot="reference">
                <el-image
                  style="width: 240px; height: 100px"
                  :src="scope.row.src"
                ></el-image> </el-button
            ></el-popover>
          </template>
        </el-table-column>
        <el-table-column
          prop="notes"
          label="说明"
          width="180"
        ></el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="text" size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-drawer
      title="添加轮播图"
      :before-close="handleClose"
      :visible.sync="dialog"
      direction="ltr"
      custom-class="demo-drawer"
      ref="drawer"
    >
      <div class="demo-drawer__content">
        <el-form :model="form">
          <el-form-item label="图片" :label-width="formLabelWidth">
            <!-- http://localhost:8081/tool/upload/ -->
            <div>
              <el-upload
                class="upload-demo"
                action="http://192.168.142.30:8081/tool/upload/"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                multiple
                :limit="3"
                :on-exceed="handleExceed"
                :on-success="handleSuccess"
                v-model="form.src"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </div>
            <div>
              <!-- <input type="file" @change="onFileChangeImg" />
              <button @click="uploadFiles()">上传</button> -->
            </div>
          </el-form-item>
          <el-form-item label="说明" :label-width="formLabelWidth">
            <el-input v-model="form.notes" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button
            type="primary"
            @click="$refs.drawer.closeDrawer()"
            :loading="loading"
            >{{ loading ? "提交中 ..." : "确 定" }}</el-button
          >
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { getListCarousel } from "@/api/carousel";
import { deleteCarouselById } from "@/api/carousel";
import { addCarousel } from "@/api/carousel";
import { deleteFile } from "@/api/tool";
// import axios from "axios";
export default {
  data() {
    return {
      tableData: [
        {
          id: "",
          src: "",
          notes: "",
        },
      ],
      table: false,
      dialog: false,
      loading: false,
      form: {
        src: "",
        notes: "",
      },
      formLabelWidth: "80px",
      timer: null,
      selectedFileImg: "",
      visible: false,
      dialogImageUrl: "",
      dialogVisible: false,
      upStatus: false,
    };
  },
  methods: {
    getCarousel() {
      getListCarousel().then((res) => {
        this.tableData = res.data;
      });
    },
    handleClick(row) {
      console.log(row);
      const c = {
        id: row.id,
      };
      deleteCarouselById(c).then((res) => {
        if (res.code === 0) {
          this.getCarousel();
          this.$message({
            showClose: true,
            message: "删除成功",
          });
        } else {
          this.$message({
            showClose: true,
            message: "删除失败",
            type: "warning",
          });
        }
      });
    },
    handleClose(done) {
      if (this.loading) {
        return;
      }
      this.$confirm("确定要提交表单吗？")
        .then((_) => {
          this.loading = true;
          this.timer = setTimeout(() => {
            console.log("form===>", this.form);

            //location.reload();
            const st = this.upStatus;
            if (st) {
              addCarousel(this.form).then((res) => {
                if (res.code === 0) {
                  this.form = "";
                  this.form.src = "";
                }
              });
            }

            done();
            // 动画关闭需要一定的时间
            setTimeout(() => {
              this.loading = false;
              this.$message({
                showClose: true,
                message: "提交完成",
                type: "warning",
              });
              this.getCarousel();
            }, 400);
          }, 2000);
        })
        .catch((_) => {});
    },
    cancelForm() {
      this.loading = false;
      this.dialog = false;
      clearTimeout(this.timer);
    },
    // onFileChangeImg(e) {
    //   this.selectedFileImg = e.target.files[0];
    //   this.form.src = this.selectedFileImg.name;
    // },
    // uploadFiles() {
    //   const formData = new FormData();
    //   formData.append("file", this.selectedFileImg);

    //   //http://localhost:8081/tool/upload/
    //   //192.168.142.30
    //   axios
    //     .post("http://192.168.142.30:8081/tool/upload/", formData, {
    //       headers: {
    //         "Content-Type": "multipart/form-data",
    //       },
    //     })
    //     .then((response) => {
    //       if (response.data.code === 0) {
    //         this.$message({
    //           message: "添加成功",
    //           type: "success",
    //         });
    //       } else {
    //         this.$message.error("上传失败");
    //       }
    //     })
    //     .catch((error) => {
    //       console.error(error);
    //     });
    // },

    handleRemove(file, fileList) {
      console.log(file, fileList);
      const path = {
        filePath: file.response.url,
      };
      console.log(path);
      deleteFile(path).then((res) => {
        console.log(res);
      });
    },
    handlePreview(file) {
      console.log("file==>", file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleSuccess(response, file, fileList) {
      this.upStatus = false;
      // 上传成功后，设置文件名到表单数据
      //this.form.src = file.name;
      this.form.src = response.url;
      console.log(this.form.src);
      this.$message({
        showClose: true,
        message: "上传成功",
      });
      this.upStatus = true;
      file.name = response.url;
    },
  },
  created() {
    this.getCarousel();
  },
  mounted() {},
};
</script>
